package com.tm.fiverole.security.service;

import com.tm.fiverole.entity.UserEntity;
import com.tm.fiverole.mapper.RoleMapper;
import com.tm.fiverole.mapper.UserMapper;
import com.tm.fiverole.security.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 11.11新建一个用于从数据库通过用户名查询用户信息的类
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        // 调用方法查询用户


        UserEntity userEntity = userMapper.getUserByUsername(username);
        if (userEntity == null) {
            throw new RuntimeException("用户不存在");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<String> roleNameList = roleMapper.queryRoleNameListByUserId(userEntity.getId());
        for (String roleName : roleNameList) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + roleName));
        }

        User user = new User();
        user.setId(userEntity.getId());
        user.setUsername(userEntity.getUsername());
        user.setPassword(userEntity.getPassword());
        user.setAuthorities(authorities);
        return user;
    }
}